package com.aaa.gs.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * fileName:MyRandomRule
 * description:
 * author: Mr.Ge
 * createTime:2020/11/18 20:08
 * version:1.0.0
 */
public class MyRandomRule extends AbstractLoadBalancerRule {
    public MyRandomRule() {
    }

    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        System.out.println("ILoadBalancer:开始"+lb+"结束");
        if (lb == null) {
            return null;
        } else {
            Server server = null;
    //
            while(server == null) {
                //interrupted线程中断
                if (Thread.interrupted()) {
                    return null;
                }
                //getReachableServers获取可达（可用服务器）
                List<Server> upList = lb.getReachableServers();
                System.out.println("可用服务器"+upList);
                //获取所有服务器
                List<Server> allList = lb.getAllServers();
                System.out.println("所有服务器"+allList);
                //获取所有服务器数量
                int serverCount = allList.size();
                System.out.println("所有服务器数量"+serverCount);
                if (serverCount == 0) {
                    return null;
                }
                //使用随机算法    serverCount3
                int index = this.chooseRandomInt(serverCount);
                System.out.println("随机结果"+index);
                //选择服务器
                server = (Server)upList.get(index);
                if (server == null) {
                    //让出当前CPU时间，线程终端
                    Thread.yield();
                } else {
                    //判断服务是否存活
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    /**
     * 算法
     * @param serverCount
     * @return
     */
    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }
@Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    /**
     * 初始化配置
     * @param clientConfig
     */
    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
